package com.example.libraryapp.activity.bookList;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.libraryapp.Constant;
import com.example.libraryapp.R;
import com.example.libraryapp.activity.bookDetail.BookDetailActivity;
import com.example.libraryapp.adapter.BookAdapter;
import com.example.libraryapp.adapter.base.BaseAdapter;
import com.example.libraryapp.bean.Book;
import com.example.libraryapp.bean.BookType;
import com.example.libraryapp.bean.response.BaseResponse;
import com.example.libraryapp.network.base.BaseActivity;
import com.example.libraryapp.util.ToastUtil;
import com.example.libraryapp.widget.CnToolbar;

import java.io.Serializable;
import java.util.List;

/**
 * @author 伍凯铭
 * @since 2020/6/22
 */
public class BookListActivity extends BaseActivity<BookListContract.View, BookListPresenterIml>
        implements View.OnClickListener, BookListContract.View,BaseAdapter.OnItemClickListener{

    private BookType mBookType;

    private BookAdapter mBookAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Serializable serializable = getIntent().getSerializableExtra(Constant.TYPE_DATA);
        if(serializable == null) {
            this.finish();
        }
        mBookType = (BookType) serializable;
        mToolbar.setTitle(mBookType.getTypeName());
    }

    @Override
    public void onItemClick(View view, int position) {
        Book book = mBookAdapter.getItem(position);
        Intent intent = new Intent(BookListActivity.this, BookDetailActivity.class);
        intent.putExtra(Constant.BOOK_ID,book.getBookId());
        startActivity(intent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        showLoading();
        mPresenter.getBooksByType(mBookType.getTypeId());
    }

    @Override
    protected void initToolBar(CnToolbar toolbar) {
        toolbar.setBackBtnOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        finish();
    }

    @Override
    public void showBooks(BaseResponse<List<Book>> response) {
        mBookAdapter.refreshData(response.getResult());
    }

    @Override
    protected void initView(View view) {
        RecyclerView recyclerView = view.findViewById(R.id.recycler_view);
        mBookAdapter = new BookAdapter(this);
        mBookAdapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,RecyclerView.VERTICAL,false));
        recyclerView.setAdapter(mBookAdapter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_book_list;
    }

    @Override
    protected BookListPresenterIml initPresenter() {
        return new BookListPresenterIml();
    }
}
